package com.net.wanjian.networkhospitalmanager.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.evaluate.EvaluateListFragment;
import com.net.wanjian.networkhospitalmanager.adapter.base.RecyclerBaseAdapter;
import com.net.wanjian.networkhospitalmanager.bean.SearchEvaluateResult;
import com.net.wanjian.networkhospitalmanager.bean.evaluate.SaveEvaluationItemBean;
import com.net.wanjian.networkhospitalmanager.bean.evaluate.SaveEvaluationReturnResult;
import com.net.wanjian.networkhospitalmanager.bean.evaluate.SubmitEvaluateItemBean;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.utils.PicassoUtil;
import com.net.wanjian.networkhospitalmanager.utils.ProgressDialogUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.ToastUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;
import com.net.wanjian.networkhospitalmanager.view.CircleImageView;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.observers.DisposableObserver;

/**
 * Description: 简易评价 去评价列表item
 * Created by lidongcai on 17/7/18.
 * Email:  lidongcaiocc@163.com
 */
public class SimpleEvaluateAdapter extends RecyclerBaseAdapter<SubmitEvaluateItemBean, SimpleEvaluateAdapter.Viewholder> {

    private final Gson gson;
    private SearchEvaluateResult.DataBean.EventListBean mSimpleEvent;
    private LocalBroadcastManager localBroadcastManager;

    public SimpleEvaluateAdapter(Context context, SearchEvaluateResult.DataBean.EventListBean simpleEvent) {
        super(context);
        mSimpleEvent = simpleEvent;
        gson = new Gson();
        localBroadcastManager = LocalBroadcastManager.getInstance(context);
    }

    @Override
    public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_simple_evaluate, parent, false);
        AutoUtils.auto(view);
        return new Viewholder(view);
    }

    @Override
    public void onBindViewHolder(final Viewholder holder, final SubmitEvaluateItemBean item, final int position) {
        //在这里处理对事件或对老师
        holder.simpleEvaluateRoleTv.setText(URLDecoderUtil.getDecoder(item.getEvaluationTypeName()));

        if (item.getIsEvaluated() == 0) {
            //没评价过
            holder.simpleEvaluateSubmitBtn.setVisibility(View.VISIBLE);
            holder.simpleEvaluateCommentContentTv.setVisibility(View.VISIBLE);
            holder.simpleEvaluateCommentShowContentTv.setVisibility(View.GONE);
            holder.simpleEvaluateCommentContentTv.setText("");
        } else {
            //评价过
            holder.simpleEvaluateSubmitBtn.setVisibility(View.GONE);
            holder.simpleEvaluateCommentContentTv.setVisibility(View.GONE);
            holder.simpleEvaluateCommentShowContentTv.setVisibility(View.VISIBLE);

            if (URLDecoderUtil.getDecoder(item.getEvaluationTextContentInfo()).equals("")){
                holder.simpleEvaluateCommentShowContentTv.setText(R.string.no_evaluate_content);
            }else {
                holder.simpleEvaluateCommentShowContentTv.setText(URLDecoderUtil.getDecoder(item.getEvaluationTextContentInfo()));
            }
        }


        //老师信息
        if (item.getEvaluationType() == 0) {
            holder.simpleEvaluateCommentContentTv.setHint("请对老师进行评价");
            holder.simpleEvaluateDoctorInfoLayout.setVisibility(View.VISIBLE);
            if (URLDecoderUtil.getDecoder(item.getEvaluatedUserInfo().getJobTitle()).equals("")){
                holder.simpleEvaluateDoctorNameTv.setText(URLDecoderUtil.getDecoder(item.getEvaluatedUserInfo().getUserInfoTrueName()));
            }else {
                holder.simpleEvaluateDoctorNameTv.setText(URLDecoderUtil.getDecoder(item.getEvaluatedUserInfo().getUserInfoTrueName()) + "（" +
                        URLDecoderUtil.getDecoder(item.getEvaluatedUserInfo().getJobTitle() + "）"));
            }

            holder.simpleEvaluateDoctorDepartmentTv.setText("科室：" + URLDecoderUtil.getDecoder(item.getEvaluatedUserInfo().getDepartment()));

            //加载图片
            PicassoUtil.loadImage(context,
                    HttpUtil.getImageUrl(SharedXmlUtil.getInstance().getHospitalId(),
                            URLDecoderUtil.getDecoder(item.getEvaluatedUserInfo().getUserInfoID()), 2),
                    R.mipmap.user, holder.simpleEvaluateDoctorHeadImageIv);
        } else {
            holder.simpleEvaluateCommentContentTv.setHint("请对事件进行评价");
            holder.simpleEvaluateDoctorInfoLayout.setVisibility(View.GONE);
        }


        //设置内部item列表adapter
        final SimpleEvaluateRatingAdapter itemAdapter = new SimpleEvaluateRatingAdapter(context,item.getIsEvaluated());
        itemAdapter.setList(item.getEvaluationItemList());
        holder.setSimpleEvaluateRatingRecycler(context, itemAdapter);

        holder.simpleEvaluateSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                HashMap<Integer, Integer> score = itemAdapter.getScore();
//                Set<Integer> keySet = score.keySet();
//                for (Iterator it = keySet.iterator(); it.hasNext();) {
//                    int next = (int) it.next();
//                    Log.e("onClick", next+"onClick: "+score.get(next) );
//                }

                saveDataHttpRequest(item, position,score,holder.simpleEvaluateCommentContentTv.getText().toString().trim());

            }
        });
    }

    //提交评价
    private void saveDataHttpRequest(SubmitEvaluateItemBean item, final int position, HashMap<Integer, Integer> score, String content) {
        int scoreSize = score.size();
        for (int i = 0; i < scoreSize; i++) {
            if (score.get(i) == 0){
                ToastUtil.showToast("请对“"+URLDecoderUtil.getDecoder(item.getEvaluationItemList().get(i).getEvaluationItemName())+"”项进行评价");
                return;
            }
        }

        ProgressDialogUtils.showProgressDialog(context, "", R.string.loading_text);

        //这里生成对象并赋值
        final List<SaveEvaluationItemBean> itemBeanList = new ArrayList<>();
        SaveEvaluationItemBean itemBean = new SaveEvaluationItemBean();
        itemBean.setBeEvaluatedUserIdentityID(URLDecoderUtil.getDecoder(item.getEvaluatedUserInfo().getUserIdentityID()));
        itemBean.setEvaluationTextContentInfo(content);
        itemBean.setEvaluationType(item.getEvaluationType());

        List<SaveEvaluationItemBean.EvaluationItemValueListBean> itemList = new ArrayList<>();
        int size = item.getEvaluationItemList().size();
        for (int i = 0; i < size; i++) {
            SaveEvaluationItemBean.EvaluationItemValueListBean bean = new SaveEvaluationItemBean.EvaluationItemValueListBean();
            bean.setEvaluationItemID(URLDecoderUtil.getDecoder(item.getEvaluationItemList().get(i).getEvaluationItemID()));
            bean.setEventEvaluationItemID(URLDecoderUtil.getDecoder(item.getEvaluationItemList().get(i).getEventEvaluationItemID()));
            bean.setEvaluationItemValueResult(score.get(i));
            itemList.add(bean);
        }

        itemBean.setEvaluationItemValueList(itemList);
        itemBeanList.add(itemBean);

        String json = "";
        json = gson.toJson(itemBeanList);
//        RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),json);

        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();

        Log.e("dave", "saveDataHttpRequest: "+"getDeviceId=="+xmlUtil.getDeviceId()+"getToken=="+xmlUtil.getToken()+"getHospitalId=="+xmlUtil.getHospitalId()+"getUserIdentity=="+
                xmlUtil.getUserIdentity()+"getEventType=="+mSimpleEvent.getEventType()+"getEventID=="+mSimpleEvent.getEventID()+"getUserIdentityId=="+xmlUtil.getUserIdentityId()+"json=="+json);

        HttpUtil.saveEvaluationTableInfo(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                xmlUtil.getUserIdentity(), mSimpleEvent.getEventType(), mSimpleEvent.getEventID(), xmlUtil.getUserIdentityId(), json, new DisposableObserver<SaveEvaluationReturnResult>() {
                    @Override
                    public void onNext(SaveEvaluationReturnResult saveEvaluationReturnResult) {
                        if (saveEvaluationReturnResult.getResult() == ErrorCodeReturn.success) {
                            //这里保存成功刷新页面
                            ToastUtil.showToast("评价提交成功");
                            //刷新评价列表
                            localBroadcastManager.sendBroadcast(new Intent(EvaluateListFragment.REFRESH_SIMPLE_EVALUATE_LIST));

                            //设置缓存集合的值
                            SaveEvaluationItemBean b = itemBeanList.get(0);
                            SubmitEvaluateItemBean bean = list.get(position);


                            if (b.getEvaluationTextContentInfo().equals("")){
                                bean.setEvaluationTextContentInfo(context.getResources().getString(R.string.no_evaluate_content));
                            }else {
                                bean.setEvaluationTextContentInfo(b.getEvaluationTextContentInfo());
                            }

                            bean.setIsEvaluated(1);

                            int size1 = b.getEvaluationItemValueList().size();
                            for (int i = 0; i < size1; i++) {
                                bean.getEvaluationItemList().get(i).setEvaluationItemValueResult(b.getEvaluationItemValueList().get(i).getEvaluationItemValueResult());
                            }
                            SimpleEvaluateAdapter.this.notifyDataSetChanged();
                        }else {
                            ToastUtil.showToast("评价失败，请尝试再次提交");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ProgressDialogUtils.dismissProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        ProgressDialogUtils.dismissProgressDialog();
                    }
                });
    }


    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    static class Viewholder extends RecyclerView.ViewHolder {
        @BindView(R.id.simple_evaluate_role_tv)
        TextView simpleEvaluateRoleTv;
        @BindView(R.id.simple_evaluate_doctor_head_image_iv)
        CircleImageView simpleEvaluateDoctorHeadImageIv;
        @BindView(R.id.simple_evaluate_doctor_name_tv)
        TextView simpleEvaluateDoctorNameTv;
        @BindView(R.id.simple_evaluate_doctor_department_tv)
        TextView simpleEvaluateDoctorDepartmentTv;
        @BindView(R.id.simple_evaluate_doctor_info_layout)
        RelativeLayout simpleEvaluateDoctorInfoLayout;
        @BindView(R.id.simple_evaluate_rating_recycler)
        RecyclerView simpleEvaluateRatingRecycler;
        @BindView(R.id.simple_evaluate_comment_content_tv)
        EditText simpleEvaluateCommentContentTv;
        @BindView(R.id.simple_evaluate_comment_show_content_tv)
        TextView simpleEvaluateCommentShowContentTv;
        @BindView(R.id.simple_evaluate_submit_btn)
        Button simpleEvaluateSubmitBtn;

        public Viewholder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void setSimpleEvaluateRatingRecycler(Context context, SimpleEvaluateRatingAdapter adapter) {
            this.simpleEvaluateRatingRecycler.setLayoutManager(new LinearLayoutManager(context));
            this.simpleEvaluateRatingRecycler.setAdapter(adapter);
        }


    }
}
